package stock.servlets;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import stock.commons.DBLoader;
import stock.commons.DBLoaderLineProcessor;
import stock.commons.FileReader;
import stock.commons.LineProcessor;
import stock.database.Coneccion;
import stock.database.DBValuesSetter;

import com.mysql.jdbc.Connection;

/**
 * 
 * @author hugo
 * @version
 */
public class UploadFile extends HttpServlet {

	private String dirUploadFiles;
	private Connection conn = null;

	public void init() throws ServletException {
		Coneccion objetconnection = new Coneccion();
		conn = (Connection) objetconnection.getConnectionBase();
		super.init();
	}

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		dirUploadFiles = "C:\\Dev\\stock\\WebContent\\upload";
		if (ServletFileUpload.isMultipartContent(request)) {
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setSizeMax(new Long(getServletContext().getInitParameter(
					"maxFileSize")).longValue());

			List listUploadFiles = null;
			FileItem item = null;

			try {
				listUploadFiles = upload.parseRequest(request);
				DBLoader loadStock = new DBLoader();
				Iterator it = listUploadFiles.iterator();
				int nroarchivo = 0;
				loadStock.deleteValuesToUploadFile(conn);
				while (it.hasNext()) {
					nroarchivo++;
					item = (FileItem) it.next();
					if (!item.isFormField()) {
						if (item.getSize() > 0) {
							String nombre = item.getName();
							String tipo = item.getContentType();
							long tamanio = item.getSize();
							String extension = nombre.substring(nombre
									.lastIndexOf("."));

							out.println("Nombre: " + nombre + "<br>");
							out.println("Tipo: " + tipo + "<br>");
							out.println("Extension: " + extension + "<br>");
							File archivo = new File(dirUploadFiles, nombre);
							item.write(archivo);

							LineProcessor processor = new DBLoaderLineProcessor(
									nroarchivo, "\",|,\"");
							FileReader.processFile(archivo, processor, conn);

							if (archivo.exists()) {
								out.println("GUARDADO "
										+ archivo.getAbsolutePath() + "</p>");
							} else {
								out.println("FALLO AL GUARDAR. NO EXISTE "
										+ archivo.getAbsolutePath() + "</p>");
							}

						}
					}
				}
				loadStock.updateStock(conn);
				loadStock.updateMovimientos(conn);
				loadStock.updateFinalReport(conn);
			} catch (FileUploadException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		out.println("La operacion finalizo correctamente! ;)");
		out.println("<p>Haga click <a href=\"http://localhost:8080/stock/jsp/listar.jsp\">aqui</a> para ver el listado</p>");
		out.close();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	public void destroy() {
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		super.destroy();
	}

}